package com.liupaik.pennmarketplace;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.MenuInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

public class SellMyItems extends Activity {
	
	//private TextView myListings;
	ListingsMyItems adapter;
	private ListView list;
	List<Listing> listings;
	String id;
	SharedPreferences user;
	private String L_id;
	private boolean hasItems;
	
	
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.myitems);
        
        hasItems = true;
        
        
//        registerForContextMenu(findViewById(R.layout.myitems));
        
        //myListings = (TextView)findViewById(R.id.myListings);
        
        user = getSharedPreferences("Users", MODE_PRIVATE);
        id = user.getString("CurrentUser", null);
       // myListings.setText();
        
        
        
        
        
        /*Button btnDelete = (Button)findViewById(R.id.deleteButton);
        btnDelete.setOnClickListener(new OnClickListener() {
			public void onClick(View v) { 
//				new AlertDialog.Builder(getParent().getParent().getParent())
//				.setMessage("Error getting data!")  
//				.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
//					public void onClick(DialogInterface dialog, int id) {
//					}
//				})
//				.show();
				
				
				String result = delete(L_id);

				//String r = reply(P_id,id,catB,text);
				//result.setText(r);
				//Intent myIntent = new Intent(v.getContext(), BuySell.class);
				//startActivityForResult(myIntent, 0);
			
				//lblResult.setText(r);
	
				
				//Intent myIntent = new Intent(v.getContext(), TabMain.class);
				//startActivityForResult(myIntent, 0);
			}
		});*/
        
        
        
        
        Button btnRefresh = (Button)findViewById(R.id.refresh_button);
		btnRefresh.setOnClickListener(new OnClickListener() {
			public void onClick(View view) {
				//				final ProgressDialog pd = ProgressDialog.show(getDialogContext(), "", "Refreshing...", true);
				//				new Thread() {
				//					public void run() {
				//						try {
				
				SellMyItems.this.populateList();
				if (hasItems){
					SellMyItems.this.makeListClickable();
					}
				//adapter.notifyDataSetChanged();

				//						}
				//						catch (Exception e){
				//							Log.e("tag",e.getMessage());
				//						}
				//						pd.dismiss();
				//					}
				//				}.start();
			}
		});

		populateList();
		
		if (hasItems){
		makeListClickable();
		}
            

            
        
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
//public static final String DELETE = "http://www.upennakpsi.org/lololol/pennmarketplace/delete.php";
//	
//	private String delete (String L_id) {
//
//		InputStream is = null;
//
//		String result = "";
//		//LinkedList<String> listings = new LinkedList<String>();
//
//		//the postings
//		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//		nameValuePairs.add(new BasicNameValuePair("L_id",L_id));
//		//nameValuePairs.add(new BasicNameValuePair("U_id",U_id));
//		//nameValuePairs.add(new BasicNameValuePair("cat",cat));
//		//nameValuePairs.add(new BasicNameValuePair("text",text));
//
//		//http post
//		try{
//			HttpClient httpclient = new DefaultHttpClient();
//			HttpPost httppost = new HttpPost(DELETE);
//			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//			HttpResponse response = httpclient.execute(httppost);            
//			HttpEntity entity = response.getEntity();
//			is = entity.getContent();                
//
//		}catch(Exception e){
//			//listings.add("Error in connecting...");
//			result = "Error in connecting...";
//			Log.e("log_tag", "Error in http connection "+e.toString());
//			return result;
//		}
//
//		//convert response to string
//		try{
//			BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
//			StringBuilder sb = new StringBuilder();
//			String line = null;
//			while ((line = reader.readLine()) != null) {
//				sb.append(line);
//			}
//			is.close();
//			result=sb.toString();
//		}catch(Exception e){
//			result = "Error in obtaining data...";
//			Log.e("log_tag", "Error converting result "+e.toString());
//			return result;
//		}
//		
//		return result;
//	}
	
	
	
	
	
	
	
	
	
	
	public static final String MYLISTINGS = "http://www.upennakpsi.org/lololol/pennmarketplace/mylistings.php";
	
	
	
	private void makeListClickable(){
		
		list.setOnItemClickListener(new OnItemClickListener() {            	
        	public void onItemClick(AdapterView<?> a, View v, int position, long id) {
        		
				Listing entry = (Listing) a.getItemAtPosition(position);

				Intent i = new Intent(SellMyItems.this, SellMyItems2.class);
				i.putExtra("id", entry.getId());
				//i.putExtra("U_id", entry.getU_id());
				i.putExtra("cat", entry.getCat());
				//i.putExtra("title", entry.getTitle());
				//i.putExtra("text", entry.getText());
				//i.putExtra("time", entry.getTime());
				//startActivityForResult(i, 0);
				View view = SellMyGroup.group.getLocalActivityManager()
				.startActivity("SellMyItems2", i
						.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
						.getDecorView();
				SellMyGroup.group.replaceView(view);
        	}
        });
		
		
	}
	
	
	private void populateList(){
		String result = getMyListings(id);
		hasItems = true;
        
        if(result.equals("Error in connecting...")){
			new AlertDialog.Builder(getParent().getParent())
			.setMessage(result)  
			.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
				}
			})
			.show();
			hasItems = false;
        }
        else if (result.equals("Error in obtaining data...")){
			new AlertDialog.Builder(getParent().getParent())
			.setMessage(result)  
			.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
				}
			})
			.show();
			hasItems = false;
        }
        else if(result.equals("No listings yet. Post something!\n")){
			/*new AlertDialog.Builder(getParent().getParent())
			.setMessage(result)  
			.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
				}
			})
			.show();*/
        	
        	Toast.makeText(
					getApplicationContext(),
					"You have no items up for sale!",
					Toast.LENGTH_SHORT)
					.show();
        	
        	hasItems = false;
    		
        	
        }
        else{
        	
        	
        	
        	
        	list = (ListView)findViewById(R.id.list);
        	
        	//ArrayAdapter<String> l = new ArrayAdapter<String>(this, R.layout.books,);
        	
        	 listings = new ArrayList<Listing>();
              	        	
        	try{
        		JSONArray jArray = new JSONArray(result);
        		for(int i=jArray.length()-1;i>=0;i--){
        			JSONObject json_data = jArray.getJSONObject(i);
        			String L_id = json_data.getString("L_id");
        			String cat = json_data.getString("cat");
        			String title = json_data.getString("title");
        			String text = json_data.getString("text");
        			String U_id = json_data.getString("U_id");
        			String time = json_data.getString("time");
        			//listings.append(L_id + " | " + cat + " | " + title + " | " + text + " | " + U_id + " | " + time + "\n");
        			
        			listings.add(new Listing(L_id,"",U_id,cat,title,text,time));
        		}
        	}
        	catch(JSONException e){
//    			new AlertDialog.Builder(SellMyItems.this)
//    			.setMessage("Error in parsing data!")  
//    			.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
//    				public void onClick(DialogInterface dialog, int id) {
//    				} 
//    			})
//    			.show();
        		
        		Toast.makeText(
						getApplicationContext(),
						"You have no items up for sale!",
						Toast.LENGTH_SHORT)
						.show();
        		
        		hasItems = false;
        		
        		
        		
//        		Log.e("log_tag", "Error parsing data "+e.toString());
        	}
        	
        	adapter = new ListingsMyItems(this, listings);            
            list.setAdapter(adapter);
        }
		
		
		
		
	}
	
	
	private String getMyListings (String id) {

		InputStream is = null;

		String result = "";
		//LinkedList<String> myListings = new LinkedList<String>();

		//the postings
		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		nameValuePairs.add(new BasicNameValuePair("id",id));

		//http post
		try{
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(MYLISTINGS);
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response = httpclient.execute(httppost);            
			HttpEntity entity = response.getEntity();
			is = entity.getContent();                

		}catch(Exception e){
			//myListings.add("Error in connecting...");
			result = "Error in connecting...";
			Log.e("log_tag", "Error in http connection "+e.toString());
			return result;
		}

		//convert response to string
		try{
			BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			is.close();
			result=sb.toString();
		}catch(Exception e){
			result = "Error in obtaining data...";
			Log.e("log_tag", "Error converting result "+e.toString());
			return result;
		}

		return result;
	}
	
	
	
	
	//public void onCreateContextMenu (ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo){
//		AdapterView.AdapterContextMenuInfo info;
//		try {
//		    info = (AdapterView.AdapterContextMenuInfo) menuInfo;
//		} catch (ClassCastException e) {
//		    Log.e("tag", "bad menuInfo", e);
//		    return;
//		}
//		long id = getListAdapter().getItemId(info.position);
		
//		super.onCreateContextMenu(menu, v, menuInfo);
//		MenuInflater inflater = getMenuInflater();
//		inflater.inflate(R.menu.context_menu, menu);
		
	//}
	
	
}